package database

import (
	"fmt"
	"zong-microservice/pkg/config"
	"zong-microservice/pkg/logger"
	"gorm.io/gorm"
	gormlogger "gorm.io/gorm/logger"
	// GORM 的 MSYQL 数据库驱动导入
	"gorm.io/driver/mysql"
)

// MysqlConnector 初始化模型
func MysqlConnector(conn ConnData) *gorm.DB {
	var err error

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%t&loc=%s",
		conn.Username, conn.Password, conn.Host, conn.Port, conn.Database, conn.Charset, true, "Local")

	gormConfig := mysql.New(mysql.Config{
		DSN: dsn,
	})

	var level gormlogger.LogLevel
	if config.Get("app", "debug") == "true" {
		// 读取不到数据也会显示
		level = gormlogger.Warn
	} else {
		// 只有错误才会显示
		level = gormlogger.Error
	}

	// 准备数据库连接池
	DB, err = gorm.Open(gormConfig, &gorm.Config{
		Logger: gormlogger.Default.LogMode(level),
	})

	logger.LogError(err)

	return DB
}
